import dayjs from 'dayjs'
import { subNum } from 'shiptools'
import { Logger, setEvent, setPage, queryString } from '../../utils/index'
import { getLinesApi, getCityLinesApi, getNoticeBoardApi, getLineByVoyageNoApi } from '../../api/index'
import { channel, WEEK_DAYS, DATE_FORMAT, DEPART_TIME_LIST, TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
import { STORAGE_KEY } from '../../utils/storage.js';
import { 
  getActiveList,
  getDisabledList,
  getSerialVoyageList,
  getCombinationProductList,
  getNormalList,
  clearLineData
} from '../list/util'

const logger = new Logger()
const pageName = TRACER_PAGES['return']

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTitle: '',
    navSubTitle: '',

    query: {},

    cityLine: {},
    startLine: {},

    lines: [],

    calData: [],

    errorConfig: {},

    empty: false,

    emptyImg: '',
    emptyTitle: '',
    emptyBtnTxt: '',
    emptyCallback: () => {},
    
    // 港口筛选
    showFilterLayout: false,
    arrivePorts: [],
    departPorts: [],
    shipNames: [],
    departTimeList: [],
    filterScrollIntoView: 'departPorts',

    selectedDeparturePort: { // 已选出发港口信息
      preList: [],
      curList: []
    },
    selectedArrivePort: { // 已选抵达港口信息
        preList: [],
        curList: []
    },
    selectedDepartureTime: { // 已选出发时间信息
        preList: [],
        curList: []
    },
    selectedShipName: { // 已选船名信息
        preList: [],
        curList: []
    },

    departPortsSelectAll: true,
    arrivePortsSelectAll: true,
    departTimeListSelectAll: true,
    shipNamesSelectAll: true,

    isFilterStatus: false,

    // 是否降序，默认为升序
    isDescending: false,
    factor: 0,
    firstLoad: true,
    wxrefid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    logger.info('onload...')
    if(options.from && options.to) {
      let title = `选返程:${options.from}-${options.to}`
      wx.setNavigationBarTitle({
        title: title
      })
    }

    if(options.end && dayjs(options.end).isBefore(dayjs())) {
      options.end = dayjs().format('YYYY-MM-DD')
      logger.warn('日期已过期')
    }
    

    // 获取 公告栏
    this.getNotice(options)

    const errorConfig = this.errConf(options)

    this.setData({
      query: options,
      errorConfig
    }, () => {
      this.getCityLineById(options)
    })
  },

  onShow: function() {
    const query = this.data.query
    const firstLoad = this.data.firstLoad
    debugger
    if(!firstLoad) {
      this.getCityLineById(query)
    }
    
    setPage(pageName + '?' + queryString(query), PRODUCT_CODE)
  },

  onError: function (err) {
    setEvent('列表', 'LB12', '^名称:'+err+'^')
  },

  errConf: function(query) {
    const that = this

    return {
      1: { // 供应商接口报错
          img: 'https://file.40017.cn/ship/ship/images/commons/list/xitongyichang.png',
          title: '系统异常...稍后重试',
          btnText: '重新查询',
          callback: function() {
            that.getCityLineById(query)
          }
      },
      2: { // 无网络
          img: '',
          title: '无可用网络，检查当前网络状态',
          btnText: '重新加载',
          callback: function() {
            that.getCityLineById(query)
          }
      },
      3: { // 当前日期无班次，查看更多日期
          img: 'https://file.40017.cn/ship/ship/images/commons/list/wuchuanpiao.png',
          title: '当天无船次',
          btnText: '查看更多日期',
          callback: function() {
            that.onGoCalendar()
          }
      },
      4: { // 城市航线错误，去程船票已包含返程船票，无需单独购买
          img: 'https://file.40017.cn/ship/ship/images/commons/list/baohanwangfan.png',
          title: '去程船票已包含返程船票，无需单独购买',
          btnText: `点击查看 ${query.from}-${query.to}航线`,
          callback: function() {
            let _query = Object.assign({from: query.to, to: query.from}, query)
            that.getCityLineById(_query)
          }
      },
      5: { // 未接入资源
          img: 'https://file.40017.cn/ship/ship/images/commons/list/weikaitong.png',
          title: '该航线暂未开通网络售票，正在洽谈中',
          btnText: `点击查看 ${query.from}-${query.to}航线`,
          callback: function() {
            let _query = Object.assign({}, query)
            _query.from = query.to
            _query.to = query.from
            that.getCityLineById(_query)
          }
      },
      6: { // 筛选后无数据
          img: 'https://file.40017.cn/ship/ship/images/wx/list/voyages-not-found.png',
          title: '抱歉，没有符合筛选条件的船次',
          btnText: '查看全部班次',
          callback: function() {
            let _query = Object.assign({}, query)
            _query.from = query.to
            _query.to = query.from
            that.getCityLineById(_query)
          }
      },
      7: { // 城市航线错误，不可单独购买该线路，但可以选择去程线路购买往返票
          img: 'https://file.40017.cn/ship/ship/images/commons/list/wuchuanpiao.png',
          title: '不可单独购买该线路，但可以选择去程线路购买往返票',
          btnText: `点击查看 ${query.from}-${query.to}航线`,
          callback: function() {
            let _query = Object.assign({}, query)
            _query.from = query.to
            _query.to = query.from
            that.getCityLineById(_query)
          }
      }
    }
  },


  getLines: function({
    date, 
    endDate,
    from, 
    to, 
    LineIds, 
    isRoundTrip,
    fromPort,
    toPort,
    supplierId, type }) {
    const that = this
    wx.showLoading({
      title: `正在加载..`
    })
    that.setData({
      lines: []
    })
    const selectedDeparturePort = that.data.selectedDeparturePort
    const selectedArrivePort = that.data.selectedArrivePort
    const selectedDepartureTime = that.data.selectedDepartureTime
    const selectedShipName = that.data.selectedShipName

    getLinesApi({
      SupplierId: supplierId,
      DepartPort: fromPort,
      ArrivePort: toPort,
      DepartDate: date,
      LineId: 0,
      IsRoundTrip: 1,
      IsReturn: 1,
      DepartCity: from,
      ArriveCity: to,
      IsShield: 0,
      DepartPorts: selectedDeparturePort.curList,
      ArrivePorts: selectedArrivePort.curList,
      DepartTimes: selectedDepartureTime.curList,
      ShipNames: selectedShipName.curList,
      LineIds: LineIds,
      Channel: channel
    }).then(response => {
      wx.hideLoading()
      if(response.status !== 200) {
        logger.tips('网络错误')
        that._getNetworkState()
        return
      }

      if(!response.data) {
        logger.tips('请求失败或者没有数据')

        that._doEmptyStuff(3)
        return
      }

      if(response.data.Data.Reason) {
        let errorType = response.data.Data.Reason
        that._doEmptyStuff(errorType)
      }

      let lines = response.data.Data.Voyages
      
      let _isEmpty = false
      if(!lines || lines.length <= 0) {
        _isEmpty = true
        if(type === 'filter') {
          that.setData({
            isFilterStatus: true
          })
        }
        that._doEmptyStuff(3)
        return
      }

      try {
        lines = clearLineData(lines, isRoundTrip)
      } catch (err) {
        console.log("err: ", err)
      }
      
      // 筛选条件
      let filters = response.data.Data.Filter

      let arrivePorts = filters.ArrivePorts || []
      let departPorts = filters.DepartPorts || []
      let shipNames = filters.ShipNames || []
      let departTimeList = DEPART_TIME_LIST

      // 对已经筛选过的条件做 isSelected 设置
      departPorts.forEach(item => {
        const _filters = selectedDeparturePort.curList.filter(port => port == item.KeyName)
        item.isSelected = _filters.includes(item.KeyName)
      })
      arrivePorts.forEach(item => {
        const _filters = selectedArrivePort.curList.filter(port => port == item.KeyName)
        item.isSelected = _filters.includes(item.KeyName)
      })
      shipNames.forEach(item => {
        const _filters = selectedShipName.curList.filter(port => port == item.KeyName)
        item.isSelected = _filters.includes(item.KeyName)
      })
      departTimeList.forEach(item => {
        const _filters = selectedDepartureTime.curList.filter(port => port == item.KeyName)
        item.isSelected = _filters.includes(item.KeyName)
      })

      // 不限怎么设置

      const departPortsSelectAll = !departPorts.filter(item => item.isSelected).length > 0
      const arrivePortsSelectAll = !arrivePorts.filter(item => item.isSelected).length > 0
      const shipNamesSelectAll = !shipNames.filter(item => item.isSelected).length > 0
      const departTimeListSelectAll = !departTimeList.filter(item => item.isSelected).length > 0

      that.setData({
        lines,
        arrivePorts,
        departPorts,
        shipNames,
        departTimeList,
        departPortsSelectAll,
        arrivePortsSelectAll,
        shipNamesSelectAll,
        departTimeListSelectAll,
        isDescending: false
      })

      setEvent('列表', 'LB11', `^出发城市:${from}^到达城市:${to}^是否灰屏:${_isEmpty? '是': '否'}^航线名称:${from}-${to}^往返程:${isRoundTrip && endDate? '往返': '单程'}^`)

    }).catch(error => {
      that._getNetworkState()
    })
  },

  _doEmptyStuff: function(type) {
    const errorConfig = this.data.errorConfig
    const errConf = errorConfig[type]

    this.setData({
      empty: true,
      emptyImg: errConf.img,
      emptyTitle: errConf.title,
      emptyBtnTxt: errConf.btnText,
      emptyCallback: errConf.callback
    })
    // errConf.callback && errConf.callback()
    
    const { from, to } = this.data
    setEvent('列表', 'LB29', `^白屏场景:${errConf.value}^航线:${from}-${to}^`)
  },

  /**
   * 生成班次服务标签列表
   * @returns {Array} 标签列表
   */
  _getServiceTagList (schedule) {
    const tagList = []
    if (schedule.Refundable) {
        tagList.push('可在线退票')
    }
    if (schedule.SupportChildrenTicket) {
        tagList.push('儿童票')
    }

    // FIXME: 暂不支持学生票
    schedule.SupportStudentTicket = false
    if (schedule.SupportStudentTicket) {
        tagList.push('学生票')
    }
    if (schedule.SupportOldTicket) {
        tagList.push('长者票')
    }
    return tagList
  },

  // 获取网络环境
  _getNetworkState: function(){
    let that = this
    wx.getNetworkType({
        success (res) {
          let errorType = 1
          if(res.networkType == 'none'){
            // 无网络（目前只能判断是否接入网络） 展示错误页面 参数：错误类型type
            errorType = 2
          } 
          that._doEmptyStuff(errorType)
        }
    })
  },

  getCityLineById: function({start, end, from, to, cityLineId, lineIds, fromPort, toPort, voyageSerialNo, seatName}) {
    const that = this
    let query = this.data.query
    query.end = end
    getCityLinesApi({
      CityLineId: cityLineId,
      Content: '',
      Type: 0,
      Channel: channel,
      DepartureCity: "",
      ArriveCity: ""
    }).then(data => {

      if(!data || data.length <= 0) {
        that.setData({
          empty: true
        })
        return
      }
      const cityLine = data.filter(item => item.DepartureCity === from && item.ArriveCity === to)[0]

      if(!cityLine) {
        that.setData({
          empty: true
        })
        return
      }
      // 获取日历 数据
      const calData = that.getCalendarData(start, end, cityLine)
      that.setData({
        query,
        cityLine,
        calData,
        firstLoad: false
      })

      // 获取去程班次详情
      that.getStartLineById({voyageSerialNo, seatName}).then(startLine => {
        // 请求班次
        that.getLines({
          date: end,
          from: cityLine.DepartureCity,
          to: cityLine.ArriveCity,
          LineIds: lineIds || [],
          isRoundTrip: 1,
          fromPort,
          toPort,
          supplierId: startLine.SupplierId
        })
      })


    })
  },

  getStartLineById: function({voyageSerialNo, seatName}) {
    const that = this
    
    return getLineByVoyageNoApi({
      voyageSerialNo
    }).then(response => {

      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.warn('停留太久..')
        return
      }

      // 设置去程nav标题

      const startLine = response.data.Data
      const navTitle = dayjs(startLine.DepartDateTime).format(`MM-DD HH:mm 出发 `) + seatName
      const navSubTitle = `${startLine.DepartPort}-${startLine.ArrivePort}`
      that.setData({
        startLine,
        navTitle,
        navSubTitle
      })

      return startLine

    }).catch(error => {
      logger.warn(error)
    })
  },

  getCalendarData: function(start, end, cityLine) {

    // 开始日期为当天  结束日期为  today + saleDays   
    const totalDays = cityLine.SaleDays
    let calData = []
    for(let i = 0; i < totalDays; i+=1) {
      const day = dayjs().add(i, 'day')
      const dayFormat = day.format('MM-DD')

      // 返程时间 要在  去程之后
      calData.push({
        day: dayFormat,
        dayFull: day.format('YYYY-MM-DD'),
        isSelected: end === day.format('YYYY-MM-DD'),
        title: `周${WEEK_DAYS[day.day()]}`,

        // 发船周期相关
        disabled: dayjs(end).isBefore(dayjs(start)) || day.isBefore(dayjs(start))
      })
    }

    return calData
  },

  /**
   * 
   * 获取公告栏内容
   * ——channel渠道 0：微信H5，1：船票通 2：APP，3：M站，4：支付宝小程序，5：百度小程序，6：PC站, 20： 腾讯出行服务船票插件，
   * 7：海安老港小程序，8：广州客轮小程序，9：泛营轮渡小程序，10：中铁轮渡小程序，11：珠海高速小程序
   * @param {Number} type 页面类型 0：首页；1：班次列表页
   * @param {*} cityLineId 城市航线ID 
   */
  getNotice: function({cityLineId, from, to}) {
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    getNoticeBoardApi({
      Type: 1,
      CityLineId: cityLineId,
      DepartureCity: from,
      ArriveCity: to,
      OpenId: openId,
      UnionId: unionId,
      Channel: 17
    }).then(response => {
    }).catch(error => {
      logger.warn(err)
    }) 
  },


  onCalChoose: function(e) {
    const that = this
    const cal = e.detail
    debugger
    if(cal.disabled) return

    let query = this.data.query
    query.end = cal.dayFull
    that.getCityLineById(query)

    this.setData({
      query
    })

    setEvent('列表', 'LB01', `^出发日期:${query.start}^航线名称:${query.from}-${query.to}^往返:往返返程^`)

  },

  onGoCalendar: function() {
    const that = this
    const query = this.data.query
    const cityLine = this.data.cityLine
    const _startDate = query.start && dayjs(query.start)
    const _endDate = query.end && dayjs(query.end)
    const _cycle = cityLine.ShipCycle
    const _saleDays = cityLine.PreSaleDays
    const _reserveDays = subNum(cityLine.PreSaleDays, cityLine.SaleDays)
    const type = 'end'
    
    const isRound = cityLine.IsRoundTripTicket === 1 && _endDate? 1: 0
    wx.navigateTo({
      url: `../calendar/index?start=${_startDate && _startDate.format(DATE_FORMAT)}&end=${_endDate && _endDate.format(DATE_FORMAT)}&isRound=${isRound}&cycle=${_cycle}&saleDays=${_saleDays}&reserveDays=${_reserveDays}&type=${type}`,
      events: {
        selectDateChannel: function({data}) {
          query.end = data.format
          that.getCityLineById(query)
        }
      }
    })
    setEvent('列表', 'LB02', `^航线名称:${query.from}-${query.to}^往返:往返返程^`)
  },

  

  /**
   * 排序
   * @param {String} type 根据什么类型来排序，type：'departureTime'
   * @param {Boolean} isDescending 是否降序排列，默认为升序
   */
  _sortBy (type, isDescending = false) {
    const that = this
    const schedules = that.data.lines
    if (!schedules) {
        return
    }
    const factor = isDescending ? -1 : 1 // 升序、降序因子
    if (type === 'departureTime') {
        // 所有班次排序
        schedules.sort((a, b) => {
            const departureTimeA = dayjs(a.DepartDateTime)
            const departureTimeB = dayjs(b.DepartDateTime)
            if (departureTimeA.isBefore(departureTimeB)) {
                return factor * -1
            }
            if (departureTimeA.isAfter(departureTimeB)) {
                return factor * 1
            }
            return 0
        })
    }
    const scheduleActive = getActiveList(schedules) // 有票且可预订的班次列表
    const scheduleDisabled = getDisabledList(schedules) // 不可预订的班次列表
    const serialVoyageList = getSerialVoyageList(scheduleActive) // 可售——流水班列表
    const combinationProductList = getCombinationProductList(scheduleActive) // 可售——组合产品列表
    const normalList = getNormalList(scheduleActive) // 可售——普通班次列表
    const disabledSerialVoyageList = getSerialVoyageList(scheduleDisabled) // 不可售——流水班列表
    const disabledCombinationProductList = getCombinationProductList(scheduleDisabled) // 不可售——组合产品列表
    const disabledNormalList = getNormalList(scheduleDisabled) // 不可售——普通班次列表
    // 组装班次列表：可点击（组合产品 + 流水班 + 普通班次） + 不可点击【停售 + 无票】（组合产品 + 流水班 + 普通班次）
    const schedulesAfterSort = [
        ...combinationProductList, 
        ...serialVoyageList, 
        ...normalList, 
        ...disabledCombinationProductList,
        ...disabledSerialVoyageList,
        ...disabledNormalList
    ]
    // 更新schedules
    // this.props.dispatch({type: 'List/setState', payload: {schedules: schedulesAfterSort}})
    // 重置当前页数
    this.setData({
      factor,
      lines: schedulesAfterSort,
      isDescending
    })
  },

  onChooseLine: function(e) {
    const line = e.currentTarget.dataset.line
    const query= this.data.query
    const lines = this.data.lines
    const cityLine = this.data.cityLine
    if(line.disabled) return

    
    if(cityLine.IsRoundTripTicket === 1 && query.end) {
      setEvent('列表', 'LB40', `^往返:返程^航线名称:${line.DepartCity}-${line.ArriveCity}^港口航线名称:${line.DepartPort}-${line.ArrivePort}^发船时间:${line.DepartDateTime}^`)
      lines.forEach(item => {
        if(item.VoyageSerialNo === line.VoyageSerialNo) {
          item.isShowSeatList = !item.isShowSeatList
        } else {
          item.isShowSeatList = false
        }
      })
      this.setData({
        lines
      })
      return
    }

    // // 多供应商
    // if(line.isShowMultiSupplier) {
    //   lines.forEach(item => {
    //     if(item.VoyageSerialNo === line.VoyageSerialNo) {
    //       item.isMultiSupplierSlide = !item.isMultiSupplierSlide
    //     } else {
    //       item.isMultiSupplierSlide = false
    //     }
    //   })
    //   this.setData({
    //     lines
    //   })
    //   return
    // }

    // wx.navigateTo({
    //   url: `../middle/index?voyageSerialNo=${line.VoyageSerialNo}&from=${line.DepartCity}&to=${line.ArriveCity}&departPort=${line.DepartPort}&lineId=${line.LineId}&isPort=0`
    // })
  },


  onChooseLineDirect: function(e) {
    const query = this.data.query
    const startLine = this.data.startLine
    const line = e.currentTarget.dataset.line
    const seat = e.currentTarget.dataset.seat
    if(line.disabled || seat.TicketLeft <= 0) {
      return
    }

    const tripSeatName = query.seatName
    const voyageSerialNo = query.voyageSerialNo // 去程班次流水号
    const returnVoyageSerialNo = line.VoyageSerialNo // 返程班次流水号
    const tripSeatInfo = startLine.ShipSeats.find(item => item.DisplayName === tripSeatName) // 去程所选舱位详情
    const seatId = tripSeatInfo ? `${tripSeatInfo.SeatType}-${tripSeatInfo.SeatId}-${tripSeatInfo.DisplayName}` : ''
    const returnSeatId = `${seat.SeatType}-${seat.SeatId}-${seat.DisplayName}`
    wx.navigateTo({
      url: `../booking/index?voyageSerialNo=${voyageSerialNo}&returnNo=${returnVoyageSerialNo}&seatId=${seatId}&returnSeatId=${returnSeatId}`
    })

    const wxrefid = this.data.wxrefid  

    if(query.end) {
      setEvent('列表', 'LB41', `^往返:去程^港口航线名称:${line.DepartPort}-${line.ArrivePort}^发船时间:${line.DepartDateTime}^舱位预订:${seat.DisplayName}`)
    } else {
      if(line.isComProduct) {
        let evLabel = line.IsReseverVoyage? 'LB31': 'LB27'
        setEvent('列表', evLabel, `^供应商:${line.SupplierName}^港口航线名称:${line.DepartPort}-${line.ArrivePort}^舱位预订:${seat.DisplayName}^`)
      } else {
        let _evLabel = line.IsReseverVoyage? 'LB30': 'LB25'
        setEvent('列表', _evLabel, `^渠道refid:${wxrefid}^航线名称:${line.DepartCity}-${line.ArriveCity}^船名:${line.ShipName}^发船时间:${line.DepartDateTime}^舱位:${seat.DisplayName}^`)
      }
    }
  },

  onChangeStartLine: function(e) {
    wx.navigateBack()
    const startLine = this.data.startLine
    setEvent('列表', 'LB42', `^往返:返程^航线名称:${startLine.DepartCity}-${startLine.ArriveCity}^港口航线名称:${startLine.DepartPort}-${startLine.ArrivePort}^更改去程:${startLine.DepartPort}-${startLine.ArrivePort}^`)
  },

  emptyHandler: function(e) {
    const emptyCallback = this.data.emptyCallback
    return emptyCallback()
  },


  
  // 港口筛选相关
  onFilterClick: function(e) {
    const type = e.currentTarget.dataset.type
    const isDescending = this.data.isDescending
    const cityLine = this.data.cityLine
    const departCity = cityLine.DepartureCity
    const arriveCity = cityLine.ArriveCity
    if(type === 'toMap') {
      this.goToMap()
      return
    }
    
    if(type === 'filterPort') {
      setEvent('列表', 'LB06', `^航线名称:${departCity}-${arriveCity}^`)
    }

    if(type === 'sortByTime') {
      this._sortBy('departureTime', !isDescending)
      setEvent('列表', 'LB07', `^航线名称:${departCity}-${arriveCity}^`)
      return
    }

    let scrollIntoView = 'departPorts'
    if(type === 'filterMore') {
      scrollIntoView = 'departTimeList'
      setEvent('列表', 'LB08', `^航线名称:${departCity}-${arriveCity}^`)
    }
    this.setData({
      filterScrollIntoView: scrollIntoView,
      showFilterLayout: true
    })
  },

  goToMap: function() {
    const lines = this.data.lines
    if(!lines || lines.length <= 0) return

    const currentLine = lines[0]
    const departCity = currentLine.DepartCity
    const arriveCity = currentLine.ArriveCity
    const departPort = currentLine.DepartPort
    const arrivePort = currentLine.ArrivePort
    const lineId = currentLine.LineId
    const isPort = !departCity && !arriveCity ? '1' : '0' // 是否通过港口查询
    const url = `../map/index?from=${departCity || departPort}&to=${arriveCity || arrivePort}&fromPort=${departPort}&toPort=${arrivePort}&lineId=${lineId}&isPort=${isPort}&canOrder=list`
    wx.navigateTo({
      url
    })
    
    setEvent('列表', 'LB03', `^航线名称:${departCity}-${arriveCity}^`)
  },

  onConfirmLayout: function() {
    const that = this

    const cityLine = that.data.cityLine
    const query = that.data.query

    // 记录上次选中的条件 在取消的时候要用到
    let selectedDeparturePort = that.data.selectedDeparturePort
    let selectedArrivePort = that.data.selectedArrivePort
    let selectedDepartureTime = that.data.selectedDepartureTime
    let electedShipName = that.data.selectedShipName

    selectedDeparturePort.preList = [...selectedDeparturePort.curList]
    selectedArrivePort.preList = [...selectedArrivePort.curList]
    selectedDepartureTime.preList = [...selectedDepartureTime.curList]
    electedShipName.preList = [...electedShipName.curList]

    // 请求班次
    that.getLines({
      date: query.start,
      endDate: query.end,
      from: cityLine.DepartureCity,
      to: cityLine.ArriveCity,
      LineIds: query.lineIds || [],
      isRoundTrip: cityLine.IsRoundTripTicket === 1,
      fromPort: query.fromPort,
      toPort: query.toPort,
      supplierId: cityLine.SupplierId,
      type: 'filter'
    })
    this.onHideLayout()
  },

  onCanelLayout: function() {
    const that = this

    // selectedDeparturePort
    // selectedArrivePort
    // selectedDepartureTime
    // selectedShipName

    let selectedDeparturePort = that.data.selectedDeparturePort
    let selectedArrivePort = that.data.selectedArrivePort
    let selectedDepartureTime = that.data.selectedDepartureTime
    let selectedShipName = that.data.selectedShipName

    selectedDeparturePort.curList = [...selectedDeparturePort.preList]
    selectedArrivePort.curList = [...selectedArrivePort.preList]
    selectedDepartureTime.curList = [...selectedDepartureTime.preList]
    selectedShipName.curList = [...selectedShipName.preList]

    // TODO:
    let departPorts = that.data.departPorts
    let arrivePorts = that.data.arrivePorts
    let departTimeList = that.data.departTimeList
    let shipNames = that.data.shipNames

    departPorts.forEach(item => {
      item.isSelected = selectedDeparturePort.curList.includes(item.KeyName)
    })
  
    arrivePorts.forEach(item => {
      item.isSelected = selectedArrivePort.curList.includes(item.KeyName)
    })
    departTimeList.forEach(item => {
      item.isSelected = selectedDepartureTime.curList.includes(item.KeyName)
    })
    shipNames.forEach(item => {
      item.isSelected = selectedShipName.curList.includes(item.KeyName)
    })

    const departPortsSelectAll = !departPorts.filter(item => item.isSelected).length > 0
    const arrivePortsSelectAll = !arrivePorts.filter(item => item.isSelected).length > 0
    const shipNamesSelectAll = !shipNames.filter(item => item.isSelected).length > 0
    const departTimeListSelectAll = !departTimeList.filter(item => item.isSelected).length > 0

    that.setData({
      departPorts,
      arrivePorts,
      departTimeList,
      shipNames,
      selectedDeparturePort,
      selectedArrivePort,
      selectedDepartureTime,
      selectedShipName,

      departPortsSelectAll,
      arrivePortsSelectAll,
      shipNamesSelectAll,
      departTimeListSelectAll
    })

    this.onHideLayout()
  },

  onHideLayout: function() {
    this.setData({
      showFilterLayout: false
    })
  },
  onTabClick: function(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      filterScrollIntoView: tab
    })

  },

  selectFilterCondition: function(e) {
    const that = this
    const type = e.currentTarget.dataset.type
    const selectedItem = e.currentTarget.dataset.item

    // 当前已选的筛选条件信息
    const curFilterConditionObj = this.data[`selected${type}`] 
    // TODO 待优化：curFilterConditionObj需要做一次深拷贝
    if (!curFilterConditionObj) {
      return
    }
    
    let departPorts = that.data.departPorts
    let arrivePorts = that.data.arrivePorts
    let departTimeList = that.data.departTimeList
    let shipNames = that.data.shipNames
    let isSelected = false

    if (selectedItem === 'all') { // 当前点击项是否为'全选/不限'按钮
        curFilterConditionObj.curList = []
        if(type === 'DeparturePort') {
          departPorts.forEach(item => {
              item.isSelected = isSelected
          })
        }
        if(type === 'ArrivePort') {
          arrivePorts.forEach(item => {
              item.isSelected = isSelected
          })
        }
        if(type === 'DepartureTime') {
          departTimeList.forEach(item => {
              item.isSelected = isSelected
          })
        }
        if(type === 'ShipName') {
          shipNames.forEach(item => {
              item.isSelected = isSelected
          })
        }
        
    } else {
        const index = curFilterConditionObj.curList.findIndex(item => item === selectedItem.KeyName)
        
        if (index === -1) { // 已选项不在当前列表中
            curFilterConditionObj.curList.push(selectedItem.KeyName)
            isSelected = true
        } else {
            curFilterConditionObj.curList.splice(index, 1)
        }

        if(type === 'DeparturePort') {
          departPorts.forEach(item => {
            if(item.KeyName === selectedItem.KeyName) {
              item.isSelected = isSelected
            }
          })
        }
        if(type === 'ArrivePort') {
          arrivePorts.forEach(item => {
            if(item.KeyName === selectedItem.KeyName) {
              item.isSelected = isSelected
            }
          })
        }
        if(type === 'DepartureTime') {
          departTimeList.forEach(item => {
            if(item.KeyName === selectedItem.KeyName) {
              item.isSelected = isSelected
            }
          })
        }
        if(type === 'ShipName') {
          shipNames.forEach(item => {
            if(item.KeyName === selectedItem.KeyName) {
              item.isSelected = isSelected
            }
          })
        }
    }
    
          
    const departPortsSelectAll = !departPorts.filter(item => item.isSelected).length > 0
    const arrivePortsSelectAll = !arrivePorts.filter(item => item.isSelected).length > 0
    const shipNamesSelectAll = !shipNames.filter(item => item.isSelected).length > 0
    const departTimeListSelectAll = !departTimeList.filter(item => item.isSelected).length > 0

    this.setData({
      [`selected${type}`]: curFilterConditionObj,
        
      departPorts,
      arrivePorts,
      departTimeList,
      shipNames,
      departPortsSelectAll,
      arrivePortsSelectAll,
      departTimeListSelectAll,
      shipNamesSelectAll
    })
  },

  onClickNoticeBar: function(e) {
    const notice = this.data.notice
    wx.showModal({
      title: '公告',
      content: notice,
      showCancel: false,
      cancelText: '取消',
      cancelColor: '#333333',
      confirmText: '确定',
      confirmColor: '#00c777',
      success: (result) => {
        if(result.confirm){
          
        }
      },
      fail: ()=>{},
      complete: ()=>{}
    });
  }
})